<template>
  <view class="container">
    <FilterNavbar :searchList="searchList" v-model:queryParam="queryParam" @confirm="onFilterNavbarConfirm">
      <template #center>
        <view class="navbar-title"> 订单同步 </view>
      </template>
    </FilterNavbar>
    <scroll-view
      scroll-y
      :scroll-top="scrollTop"
      :scroll-with-animation="true"
      refresher-enabled
      :refresher-triggered="refreshStatus"
      :enable-back-to-top="true"
      @refresherrefresh="resetRefresh(true)"
      @scrolltolower="reachBottom"
    >
      <view class="tips">
        <view :class="visiable ? '' : 'fix-hight'">
          <view style="margin-bottom: 8rpx">
            1、同步订单：根据您配置的渠道及账号密码，定时自动同步各平台订单，包含订单信息、承租人信息、车辆信息、费用信息等。
          </view>
          <view style="margin-bottom: 8rpx">
            2、同步库存：当车辆存在排车、改排、续租、换车、提前还车、取消订单等操作时，系统将自动去各个平台反占库存，防止车辆超售/超卖，造成到店无车情况发生。
          </view>
          <view>3、门店/车型/车辆/员工匹配：</view>
          <view> 如OTA平台侧配置的门店/车型/车辆/员工名称同商户在企橙系统侧创建的门店/车型/车辆/员工名称一致时，系统会自动建立关联； </view>
          <view> 如OTA平台侧与企橙系统门店/车型/车辆/员工名称对应关系为N对1时，可以手动操作关联。 </view>
          <view> 此功能会支持到平台订单同步及库存同步的及时准确性。 </view>
          <view style="margin-top: 8rpx">
            4、如您选择的维护方式为：自动维护，新创建账号后已完成的历史订单不会自动抓取，请手动操作【同步订单】。
          </view>
        </view>
        <view class="icon-box" @click="onViewClick">
          {{ visiable ? '收起更多' : '查看更多' }}
          <ve-icon
            v-if="visiable"
            :style="{
              marginLeft: '8rpx',
            }"
            name="arrow_top_1"
            size="28"
          />
          <ve-icon
            v-else
            :style="{
              marginLeft: '8rpx',
            }"
            name="arrow_bottom_1"
            size="28"
          />
        </view>
      </view>
      <view class="record-list">
        <block v-for="item in (dataSource as any)" :key="item">
          <ve-card :title="`${item.sourceName} ${item.subject}`" :sub-title="item.statusName" :type="getStatus(item.status)">
            <!-- 标签 -->
            <view class="tag-item-box" v-if="item.msgList?.length > 0">
              <ve-tag v-for="list in item.msgList" :key="list" class="tag-item" :title="list" color="rgba(229, 155, 28, 1)" plain />
            </view>
            <!-- 铁行、飞租不展示 -->
            <ve-cell v-if="[7, 8].includes(item.sourceId) == false" label="渠道账号">{{ item.username || '-' }}</ve-cell>
            <ve-cell label="最后同步时间">{{ item.lastFinishTime || '-' }}</ve-cell>
            <ve-cell label="同步库存">
              <ve-switch
                :disabled="syncInventory?.channelStoreSync == 0 || item.status == 3"
                :value="item.syncStore"
                :activeValue="1"
                :inactiveValue="0"
                @change="(check: number) => onSwitchChange(check, item)"
                :size="16"
              >
                <ve-tooltip placement="top">
                  <template #content>
                    <view>同步库存开启后，有车辆被订单占用时，</view>
                    <view>系统会自动在渠道中占用当前车辆</view>
                  </template>
                  <ve-icon name="help" color="rgba(22, 93, 255, 1)" size="64" />
                </ve-tooltip>
              </ve-switch>
            </ve-cell>
            <view class="syncStore-checkbox-box" v-if="item.syncStore === 1">
              <view class="ve-checkbox" v-for="option in item.options" :key="option.value">
                <view class="ve-checkbox__icon-wrap" @tap="toggle(item, option)">
                  <text
                    :class="['checkbox__icon-wrap__icon', 'iconfont', option.checked ? 've-icon-checked-nocolor' : 've-icon-no-check']"
                    :style="option.checked ? 'color: rgba(22, 93, 255, 1)' : 'color: rgba(255, 255, 255, 1)'"
                  />
                </view>
                <view class="ve-checkbox__label"> {{ option.label }} </view>
              </view>
            </view>
            <view class="errMsg-box" v-if="item.errorMsg">
              <text class="iconfont ve-icon-warning icon-class" style="margin-right: 18rpx"></text>
              <text>{{ item.errorMsg }}</text>
            </view>
            <ve-operate-list :operates="operates" :record="item" />
          </ve-card>
        </block>
        <!-- 加载结束列表为空时展示 -->
        <ve-empty v-if="dataSource.length == 0 && loadStatus == 'nomore'"></ve-empty>
        <!-- 底部加载状态 -->
        <ve-load-more v-else :status="loadStatus" bgColor="#F7F7F9"></ve-load-more>

        <!-- 同步状态弹窗 -->
        <ve-modal
          title="提示"
          v-model="syncStoreModalValue"
          :cancelText="cancelText"
          @cancel="onSyncStoreModalCancel"
          @confirm="onSyncStoreModalConfirm"
        >
          <view class="modal-body">{{ syncStoreModalText }}</view>
        </ve-modal>

        <ve-modal
          title="账号校验"
          v-model="feizhuTaskModalValue"
          :showConfirm="false"
          cancelText="不想等了，稍后在尝试"
          @cancel="onFeizhuTaskModalCancel"
        >
          <view class="feizhu-task-box">
            <view class="task-item">当前有其他进行中的校验任务，请您稍作等待</view>
            <view class="task-item" style="color: rgba(245, 63, 63, 1)">等待期间，请不要关闭此弹窗</view>
          </view>
        </ve-modal>

        <ve-modal title="短信验证码" v-model="smsCodeModalValue">
          <ve-form ref="smsCodeModalFormRef" :model="smsCodeModalForm" :rules="smsCodeModalRules">
            <ve-form-item valuePosition="left">
              <view>
                验证码已发送至手机号：
                <template v-if="detail.record?.sourceId === 5">
                  {{ feizhuPhone }}
                </template>
                <template v-else>
                  {{ detail.record.username }}
                </template>
              </view>
            </ve-form-item>
            <ve-form-item label="验证码" required prop="smsCode" :borderBottom="false">
              <ve-input v-model="smsCodeModalForm.smsCode" placeholder="请输入" :maxlength="20" />
              <ve-button
                v-if="detail.record?.sourceId !== 5"
                class="smscode-button"
                type="link"
                size="mini"
                :disabled="disabled"
                @click="onModalSmsCode"
              >
                {{ btnText }}
              </ve-button>
            </ve-form-item>
          </ve-form>
          <template #footer>
            <ve-button type="link" size="long" @click="onSmsCodeModalCancel" class="smsText">取消</ve-button>
            <view class="divider"></view>
            <ve-button type="link" :loading="smsModalLoading" size="long" class="smsText blue" @click="onSmsCodeModalConfirm">
              确定
            </ve-button>
          </template>
        </ve-modal>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
  import { ref, computed } from 'vue'
  import FilterNavbar from '@/components/FilterNavbar'
  import useList from '@/hooks/useList'
  import {
    changeStatusAPI,
    updateSyncStatusAPI,
    checkAccountAPI,
    checkAccountStopAPI,
    checkAccountCodeAPI,
    getDetailAPI,
  } from '@/api/order/sOrder'
  import { onShow, onLoad } from '@dcloudio/uni-app'
  import { userStore } from '@/stores'
  import useCountLoop from './hooks/useCountLoop'
  import { clearFeizhuTimer, feizhuDetailLoop, closeDialog } from './utils'
  import { usePageDict } from '@/hooks/useDict'
  const dict = usePageDict('syncChannelDicr')

  const { doLoop, clearLoop, btnText, disabled } = useCountLoop()
  const { startTimer, clearTimer } = closeDialog()

  const visiable = ref(false)
  const syncInventory = ref<any>({})
  const userInfoStore = userStore()

  const smsCodeModalFormRef = ref()
  const smsCodeModalForm = ref<any>({})
  const smsCodeModalRules = ref({
    smsCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  })
  const feizhuTaskModalValue = ref(false)
  const smsCodeModalValue = ref(false)
  const syncStoreModalValue = ref(false)
  const syncStoreModalText = ref('')
  const cancelText = ref('再想想')

  const searchList = computed(() => {
    return [
      {
        prop: 'sourceIdList',
        label: '渠道名称',
        type: 'remote-select',
        attrs: {
          title: '渠道名称',
          type: 'dict',
          multiple: true,
          outData: dict.thirdpartySourceEnum,
        },
      },
      {
        prop: 'subjectLike',
        label: '运营主体',
        type: 'input',
      },
      {
        prop: 'usernameLike',
        label: '渠道账号',
        type: 'input',
      },
      {
        prop: 'status',
        label: '账号状态',
        type: 'picker',
        attrs: {
          options: dict.accountStatusEnum,
        },
      },
    ]
  })
  const onFilterNavbarConfirm = (params: any) => {
    queryParam.value = {
      ...queryParam.value,
      ...params,
    }
    resetRefresh()
  }

  // 关闭/开启同步详情
  const detail = ref()
  const operates = ref([
    {
      label: '同步订单',
      permission: 'svmsapp:order-sync.sync',
      // 铁行、飞租没有此按钮
      show: (record: any) => record.status == 1 && record.sourceId != 7 && record.sourceId != 8,
      method: (record: any) => {
        uni.navigateTo({
          url: '/pages/order/order-sync/sync-time?id=' + record.id + '&sourceName=' + record.sourceName + '&subject=' + record.subject,
        })
      },
    },
    {
      label: '关闭',
      permission: 'svmsapp:order-sync.close',
      show: (record: any) => record.status == 1,
      method: (record: any) => {
        syncStoreModalValue.value = true
        if (record.sourceId == 7 || record.sourceId == 8) {
          syncStoreModalText.value = `请确认是否关闭当前OTA渠道，停用后${record.sourceName}渠道订单和库存将不会再同步？`
        } else {
          syncStoreModalText.value = '请确认是否关闭当前OTA渠道账号，关闭后，此OTA渠道账号的订单、门店、车辆信息以及库存将不会同步'
        }
        cancelText.value = '再想想'
        detail.value = { record, type: 0 }
      },
    },
    {
      label: '开启',
      permission: 'svmsapp:order-sync.open',
      show: (record: any) => record.status == 0,
      method: (record: any) => {
        syncStoreModalValue.value = true
        if (record.sourceId == 7 || record.sourceId == 8) {
          syncStoreModalText.value = `请确认是否开启${record.sourceName}OTA渠道，开启后，订单和库存将自动同步？`
        } else {
          syncStoreModalText.value = '请确认是否关闭当前OTA渠道账号，关闭后，此OTA渠道账号的订单、门店、车辆信息以及库存将不会同步'
        }
        cancelText.value = '关闭'
        detail.value = { record, type: 1 }
      },
    },
    {
      label: '编辑',
      permission: 'svmsapp:order-sync.edit',
      // 账号状态为同步中时，需支持操作：查看/编辑、修改密码
      show: (record: any) => record.status == 1 || record.status == 0 || record.status == 3 || record.status == 2,
      method: (record: any) => {
        uni.navigateTo({ url: '/pages/order/order-sync/form/index?id=' + record.id })
      },
    },
    {
      label: '输入验证码',
      permission: 'svmsapp:order-sync.verify',
      show: (record: any) =>
        (record.status == 1 || record.status == 0) && (record.sourceId === 2 || record.sourceId === 5) && record.verifyFlag === 0,
      method: (record: any) => {
        detail.value = { record }
        console.log(detail.value, 'record')
        if (record.sourceId === 2) {
          smsCodeModalValue.value = true
          startTimer(5 * 60 * 1000).then(() => {
            onSmsCodeModalCancel()
          })
        }
        if (record.sourceId === 5) {
          uni.showToast({
            title: '正在验证中...',
            icon: 'none',
          })

          // 弹出等待弹窗
          feizhuTaskModalValue.value = true
          // 自动调用短信验证码接口
          checkAccount()
            .then(() => {
              feizhuDetailLoop(
                (response: any) => {
                  feizhuTaskModalValue.value = false

                  if (response.verifyFlag === 1) {
                    // 不需要验证则关闭排队弹窗，直接返回，清除定时器
                    uni.showToast({
                      title: '该渠道账号无需进行验证，即将刷新...',
                      icon: 'none',
                    })
                    setTimeout(() => {
                      resetRefresh()
                    }, 500)
                  } else if (response.verifyType === 1) {
                    if (response.errMsg) {
                      uni.showToast({
                        title: response.errMsg,
                        icon: 'none',
                      })
                    } else {
                      smsCodeModalValue.value = true
                      startTimer(5 * 60 * 1000).then(() => {
                        onSmsCodeModalCancel()
                      })
                    }
                  } else {
                    uni.showToast({
                      title: '该渠道账号无需进行验证，即将刷新...',
                      icon: 'none',
                    })
                    setTimeout(() => {
                      resetRefresh()
                    }, 500)
                  }
                },
                (error: any) => {
                  feizhuTaskModalValue.value = false
                  uni.showToast({
                    title: error.message,
                    icon: 'none',
                  })
                },
                getDetailFn,
                true,
              )
            })
            .catch((err: any) => {
              feizhuTaskModalValue.value = false
              uni.showToast({
                title: err.message,
                icon: 'none',
              })
            })
        }
      },
    },
  ])

  const toggle = (item: any, options: any) => {
    item.options.forEach((option: any) => {
      if (option.value === options.value) {
        option.checked = !option.checked
      }
    })
    onSwitchChange(1, item)
  }
  const options = [
    {
      label: '短租',
      checked: false,
      value: 1,
    },
    {
      label: '长租',
      checked: false,
      value: 2,
    },
  ]
  const queryParam = ref({})
  const { resetRefresh, reachBottom, loadData, scrollTop, loadStatus, refreshStatus, dataSource } = useList(
    '/V5/channelAccount/pageList',
    queryParam,
    (data: any) => {
      data.forEach((item: any) => {
        item.options = JSON.parse(JSON.stringify(options))
        if (item.syncStoreBizList.length > 0) {
          item.options.forEach((option: any) => {
            const index = item.syncStoreBizList.findIndex((e: any) => e == option.value)
            if (index != -1) {
              item.options[index].checked = true
            }
          })
        } else {
          options.forEach((option) => {
            option.checked = false
          })
        }
      })
    },
  )

  const onViewClick = () => {
    visiable.value = !visiable.value
  }

  const feizhuPhone = ref('')
  // 详情接口函数
  const getDetailFn = async () => {
    const { result } = await getDetailAPI({ id: detail.value.record.id })
    const { extraDataJson } = result as any
    const { verifyPhone } = extraDataJson
    feizhuPhone.value = verifyPhone
    return result
  }

  // 不想等了，稍后在尝试
  const onFeizhuTaskModalCancel = () => {
    checkAccountStopAPI({ msgId: feizhuTaskId.value }).then((res: any) => {
      console.log(res, 'onFeizhuTaskModalCancel')
      feizhuTaskModalValue.value = false
      clearFeizhuTimer()
    })
  }

  // 获取验证码
  const onModalSmsCode = () => {
    const isLoop = doLoop()

    if (isLoop) {
      return
    }

    checkAccount()
  }

  // 账号验证
  const feizhuTaskId = ref() // 飞猪终止队列id
  const checkAccount = () => {
    return new Promise((resolve, reject) => {
      checkAccountAPI({ id: detail.value.record.id })
        .then((res: any) => {
          console.log(res, 'checkAccountAPI')
          // 飞猪平台会返回终止队列id
          if (res.result) {
            feizhuTaskId.value = res.result
          } else {
            uni.showToast({
              title: '验证码发送成功',
              icon: 'none',
            })
          }
          resolve(res)
        })
        .catch((err: any) => {
          console.log(err, 'err')

          uni.showToast({
            title: err.message,
            icon: 'none',
          })
          reject(err)
        })
    })
  }

  // 短信验证码取消
  const onSmsCodeModalCancel = () => {
    smsCodeModalValue.value = false
    smsCodeModalForm.value = {}
    btnText.value = '获取验证码'
    disabled.value = false
    clearLoop()
    clearTimer()

    checkAccountStopAPI({ id: detail.value.record.id }).then((res: any) => {
      console.log(res, 'onSmsCodeModalCancel')
    })
  }

  const smsModalLoading = ref(false)
  // 短信验证码确认
  const onSmsCodeModalConfirm = () => {
    smsModalLoading.value = true
    smsCodeModalFormRef.value.validate(async (valid: any) => {
      console.log(valid, 'valid')

      if (valid) {
        try {
          // 填写验证码接口
          const result = await checkAccountCodeAPI({ id: detail.value.record.id, smsCode: smsCodeModalForm.value.smsCode })
          console.log(result, 'result')

          if (detail.value.record.sourceId === 5) {
            feizhuDetailLoop(
              (response: any) => {
                if (response.closeMsg) {
                  uni.showToast({
                    title: response.closeMsg,
                    icon: 'none',
                  })
                  smsModalLoading.value = false
                } else if (response.verifyFlag === 1) {
                  smsCodeModalValue.value = false
                  smsModalLoading.value = false
                  smsCodeModalForm.value = {}
                  resetRefresh()
                } else if (response.verifyType === 1) {
                  if (response.errMsg) {
                    uni.showToast({
                      title: response.errMsg,
                      icon: 'none',
                    })
                    smsModalLoading.value = false
                  } else {
                    response.loop()
                  }
                } else if (response.verifyType === 0) {
                  smsCodeModalValue.value = false
                  smsModalLoading.value = false
                  smsCodeModalForm.value = {}
                  resetRefresh()
                }
              },
              (error: any) => {
                uni.showToast({
                  title: error.message,
                  icon: 'none',
                })
                smsModalLoading.value = false
              },
              getDetailFn,
            )
          } else {
            smsCodeModalValue.value = false
            smsModalLoading.value = false
            smsCodeModalForm.value = {}
            resetRefresh()
          }
        } catch (error: any) {
          clearFeizhuTimer()
          uni.showToast({
            title: error.data.message,
            icon: 'none',
          })
          smsModalLoading.value = false
        }
      } else {
        smsModalLoading.value = false
      }
    })
  }

  // 同步状态取消
  const onSyncStoreModalCancel = () => {
    syncStoreModalValue.value = false
    detail.value = null
    syncStoreModalText.value = ''
  }

  // 同步状态确认
  const onSyncStoreModalConfirm = () => {
    changeStatusAPI({ id: detail.value.record.id, status: detail.value.type }).then(() => {
      if (detail.value.type == 0) {
        uni.showToast({
          title: '关闭成功',
          icon: 'none',
        })
      } else {
        uni.showToast({
          title: '启用成功',
          icon: 'none',
        })
      }
      detail.value = null
      syncStoreModalValue.value = false
      resetRefresh()
    })
  }

  // 同步库存switch
  const onSwitchChange = (check: number, item: any) => {
    item.syncStore = check
    const syncStoreBizList = item.options.filter((option: any) => option.checked).map((option: any) => option.value)

    updateSyncStatusAPI({ id: item.id, syncStore: check, syncStoreBizList })
      .then((res: any) => {
        console.log(res, 'res')
        uni.showToast({
          title: '操作成功',
          icon: 'none',
        })
      })
      .catch((err: any) => {
        console.log(err, 'err')
        uni.showToast({
          title: err.message,
          icon: 'none',
        })
        item.syncStore = 0
      })
  }

  const getStatus = (status: number) => {
    const statusMap: { [key: number]: string } = {
      0: 'gray',
      1: 'blue',
      2: 'yellow',
      3: 'green',
    }
    return statusMap[status] || 'gray' // 使用默认值 'gray'
  }

  onLoad(() => {
    loadData()
    userInfoStore.setEpDetail(false).then((response: any) => {
      console.log('syncInventory', response)
      syncInventory.value = response.config
    })
  })

  onShow(() => {
    resetRefresh()
  })
</script>

<style lang="less" scoped>
  .tips {
    width: 100%;
    background: #e8f3ff;
    padding: 18rpx 32rpx;
    font-size: 24rpx;
    font-weight: 400;
    color: #191c27;

    .fix-hight {
      height: 80rpx;
      overflow: hidden;
    }

    .icon-box {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 44rpx;
      margin-top: 8rpx;
      font-size: 12px;
      font-weight: 400;
      color: #165dff;
    }
  }
  .container {
    height: 100vh;
    background: #f7f8fa;
  }
  .feizhu-task-box {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-bottom: 24rpx;
  }
  .smscode-button {
    min-width: 150rpx;
    width: 290rpx;
    padding-right: 0 !important;
  }
  .record-list {
    padding: 24rpx 24rpx;
  }
  .syncStore-checkbox-box {
    display: flex;
    align-items: center;
    padding: 0 24rpx;
    margin-top: 8rpx;
    margin-bottom: 32rpx;
    height: 92rpx;
    background: #f7f8fa;
    border-radius: 0rpx 0rpx 0rpx 0rpx;
    :deep(.radio_class) {
      justify-content: flex-start;
    }
  }
  .ve-tooltip {
    font-size: 0;
    margin-left: 16rpx;
    :deep(.ve_tooltip_content) {
      font-size: 0;
    }
    image {
      width: 18px !important;
      height: 18px !important;
    }
  }

  .card-footer {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx 0;

    .operate-list {
      width: 100%;
      font-size: 28rpx;
      font-weight: 400;
      color: #8491a8;
    }

    .ve-button {
      margin-left: 24rpx;
      margin-bottom: 24rpx;
    }
  }
  .tag-item-box {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .tag-item {
      padding-right: 18rpx;
      margin-bottom: 18rpx;
      font-size: 24rpx;
      font-weight: 400;
    }
    padding-top: 24rpx;
    margin-bottom: -10rpx;
  }
  .errMsg-box {
    font-size: 28rpx;
    font-weight: 400;
    color: #f53f3f;
    padding-top: 8rpx;
    padding-bottom: 24rpx;
  }
  .icon-class {
    font-size: 32rpx;
    margin-right: 8rpx;
  }
  .modal-body {
    padding: 0 32rpx 32rpx;
  }

  .ve-checkbox {
    display: flex;
    align-items: center;
    margin-right: 32rpx;
    .ve-checkbox__label {
      font-size: 28rpx;
      font-weight: 400;
      color: #1d2129;
      margin-left: 16rpx;
    }
  }
  .ve-checkbox__icon-wrap {
    .checkbox__icon-wrap__icon {
      font-size: 38rpx;
    }
  }
</style>
